//
//  CWTabWidget.m
//  CWDevelop
//
//  Created by LittoCats on 7/16/14.
//  Copyright (c) 2014 Littocats. All rights reserved.
//

#import "CWTabWidget.h"
#import "CWCore.h"
#import "CWBaseView.h"

#import "UIImage+CW.h"
#import "UIColor+CW.h"

@interface CWTabWidget ()<UINavigationControllerDelegate,CWTabBarDelegate, UIScrollViewDelegate>

@end

@implementation CWTabWidget

- (id)init
{
    self = [super init];
    if (self) {
        self.contents = [NSMutableDictionary new];
        
        self.contentNavigator = [[UINavigationController alloc] init];
        [_contentNavigator setNavigationBarHidden:YES];
        _contentNavigator.delegate = self;
        [_contentNavigator.view setBackgroundColor:[UIColor redColor]];
        [self addSubview:_contentNavigator.view];
        
        NSMutableArray *tabBarItems = [NSMutableArray new];
        for (int i = 0; i < [self.attributes[@"tabs"] count]; i++) {
            NSMutableDictionary *tabBarItemAttributes = self.attributes[@"tabs"][i];
            [tabBarItemAttributes setObject:@"CWTabBarItem" forKey:@"type"];
            CWTabBarItem *tabBarItem = [CWTabBarItem instanceWithJSONLayout:tabBarItemAttributes];
            [tabBarItems addObject:tabBarItem];
        }
        self.tabBar = [[CWTabBar alloc] initWithItems:tabBarItems];
        [_tabBar setBackgroundColor:[UIColor yellowColor]];
        _tabBar.delegate = self;
        [self addSubview:_tabBar];
    }
    return self;
}

#pragma mark- 
- (void)didMoveToWindow
{
    if (!_tabBar.currentItem)
        [_tabBar selectItemAtIndex:0];
}

#pragma mark- CWTabBarDelegate
- (void)tabBar:(CWTabBar *)tabBar didSelectItem:(CWTabBarItem *)item atIndex:(NSInteger)index
{
    //更新content
    NSMutableDictionary *card = [NSMutableDictionary dictionaryWithDictionary:item.attributes[@"card"]];
    NSArray *entries = [card[@"path"] componentsSeparatedByString:@">>"];
    NSString *path = [entries firstObject];
    NSString *identifier = [entries lastObject];
    
    if (!identifier || [identifier rangeOfString:@"/"].location != NSNotFound)
        identifier = [[path componentsSeparatedByString:@"/"] lastObject];
        
    
    if (!identifier || [identifier isEmpty]){
        CWLog(@"CWTabWidget error : tab%li's card content path is undefined or wrong .",(long)index);
        return;
    }
    
    UIViewController *vc = _contents[identifier];
    if (!vc) {
        [card setObject:[NSString stringWithFormat:@"%@/%@",[CWFile appRootPath],path] forKey:@"__path"];
        [card setObject:identifier forKey:@"identifier"];
        vc = [self tabContent:card];
        [_contents setObject:vc forKey:identifier];
    }
    
    //处理返回键
    vc.navigationItem.hidesBackButton = YES;
    if ([[_contentNavigator viewControllers] containsObject:vc]) {
        [_contentNavigator popToViewController:vc animated:YES];
        
    }else{
        [_contentNavigator pushViewController:vc animated:YES];
    }
}

- (UIViewController *)tabContent:(NSMutableDictionary *)properties
{
    if (properties[@"identifier"] && ![properties[@"identifier"] isEmpty]) {
        [properties addEntriesFromDictionary:properties[@"params"]];
        return [[CWViewController alloc] initWithIdentifier:properties[@"identifier"] params:properties];
    }
    return [UIViewController new];
}
#pragma mark- layout
- (void)setFrame:(CGRect)frame
{
    CGRect oldFrame = self.frame;
    [super setFrame:frame];
    
    if (fabsf(frame.size.width - oldFrame.size.width) > 0.5 || fabsf(frame.size.height - oldFrame.size.height) > 0.5)
        [self setNeedsLayout];
}

- (void)layoutSubviews
{
    [_contentNavigator.view setFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - _tabBar.frame.size.height)];
    
    [_tabBar setFrame:CGRectMake(0, _contentNavigator.view.frame.size.height, self.frame.size.width, _tabBar.frame.size.height)];
}

#pragma mark-
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [UIApplication sharedApplication].keyWindow.userInteractionEnabled = NO;
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [UIApplication sharedApplication].keyWindow.userInteractionEnabled = YES;
}
@end

@interface CWTabBar ()

@property (nonatomic, strong) UIView *headerLine;

@property (nonatomic, weak) CWTabBarItem *currentItemSelected;

@end

@implementation CWTabBar

- (instancetype)initWithItems:(NSArray *)items
{
    self = [super init];
    if (self) {
        self.headerLine = [[UIView alloc] init];
        [_headerLine setBackgroundColor:[UIColor lightGrayColor]];
        [self addSubview:_headerLine];
        
        self.items = items;
        for (CWTabBarItem *item in _items) {
            [self addSubview:item];
            [item addTarget:self action:@selector(itemSelected:) forControlEvents:UIControlEventTouchUpInside];
        }
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
//        self.pagingEnabled = YES;
    }
    return self;
}

- (void)selectItemAtIndex:(NSInteger)index
{
    if (_items.count > index)
        [self itemSelected:_items[index]];
}

#pragma mark- layout subviews
- (void)setFrame:(CGRect)frame
{
    CGRect oldFrame = self.frame;
    frame.size.height = 54.0;//tabBar 固定高度
    [super setFrame:frame];
    
    if (fabsf(frame.size.width - oldFrame.size.width) > 0.5 || fabsf(frame.size.height - oldFrame.size.height) > 0.5)
        [self setNeedsLayout];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    //计算item 宽度，最小宽度 44
    NSInteger itemCount = self.frame.size.width / 54;
    itemCount = itemCount < _items.count ? itemCount : _items.count;
    CGFloat itemWidth = self.frame.size.width / itemCount;
    
    for (int index = 0; index < [_items count]; index ++) {
        CWTabBarItem *item = _items[index];
        [item setFrame:CGRectMake(itemWidth * index, 1, itemWidth, 53)];
    }
    [self setContentSize:CGSizeMake(itemWidth * self.items.count, 54)];
    [_headerLine setFrame:CGRectMake(0, 0, itemWidth * self.items.count, 1)];
}

#pragma mark-
- (void)itemSelected:(CWTabBarItem *)item
{
    if (_currentItemSelected)
        [_currentItemSelected setSelected:NO];
    self.currentItemSelected = item;
    [item setSelected:YES];
    
    NSInteger index = [_items indexOfObject:item];
    //选中的item尽量排到中间
    
    if ([self.delegate respondsToSelector:@selector(tabBar:didSelectItem:atIndex:)])
        [self.delegate tabBar:self didSelectItem:item atIndex:index];
}
@end

@interface CWTabBarItem ()

@property (nonatomic, strong) UIImageView *imageView;

@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation CWTabBarItem

- (id)init
{
    self = [super init];
    if (self) {
        self.imageView = [[UIImageView alloc] initWithImage:self.image];
        [_imageView setFrame:CGRectMake(0, 0, 34, 34)];
        [self addSubview:_imageView];
        
        self.titleLabel = [[UILabel alloc] init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textColor = [UIColor redColor];
        _titleLabel.font = [UIFont systemFontOfSize:11];
        _titleLabel.text = self.attributes[@"text"];
        [_titleLabel sizeToFit];
        [self addSubview:_titleLabel];
        
        [self setSelected:NO];
    }
    return self;
}

- (void)setSelected:(BOOL)selected
{
    if (selected) {
        [_imageView setImage:self.imageSelected];
//        [_titleLabel setTextColor:[self titleColorSelected]];
        [self setBackgroundColor:self.backgroundColorSelected];
    }else{
        [_imageView setImage:self.image];
//        _titleLabel.textColor = self.titleColor;
        [self setBackgroundColor:[self backgroundColorUnselected]];
    }
}

#pragma mark- layout

- (void)setFrame:(CGRect)frame
{
    CGRect oldFrame = self.frame;
    [super setFrame:frame];
    
    if (fabsf(frame.size.width - oldFrame.size.width) > 0.5 || fabsf(frame.size.height - oldFrame.size.height) > 0.5)
        [self setNeedsLayout];
}

- (void)layoutSubviews
{
    [_imageView setCenter:CGPointMake(self.frame.size.width/2.0, 21)];
    
    [_titleLabel setCenter:CGPointMake(self.frame.size.width/2.0, 38 + _titleLabel.frame.size.height/2)];
}

#pragma mark-
- (UIImage *)image
{
    NSString *imageName = self.attributes[@"image"];
    UIImage *image = imageName ? [UIImage imageWithScript:imageName] : nil;
    return image ? image : [UIImage imageNamed:@"CWTabBarItemImageDefault"];
}
- (UIImage *)imageSelected
{
    NSMutableString *imageName = self.attributes[@"imageSelected"];
    if (!imageName) {
        imageName = [NSMutableString stringWithString:self.attributes[@"image"] ? self.attributes[@"image"] : @""];
        [imageName insertString:@"_selected" atIndex:imageName.length - [[[imageName componentsSeparatedByString:@"."] lastObject] length]];
        [self.attributes setObject:imageName forKey:@"imageSelected"];
    }
    UIImage *image = [UIImage imageWithScript:imageName];
    return image ? image : [UIImage imageNamed:@"CWTabBarItemImageDefault_selected"];
}

- (UIColor *)titleColor
{
    UIColor *color = [UIColor colorWithScript:self.attributes[@"textColor"]];
    return color ? color : [UIColor lightGrayColor];
}
- (UIColor *)titleColorSelected
{
    UIColor *color = [UIColor colorWithScript:self.attributes[@"textColorSelected"]];
    return color ? color : [UIColor blueColor];
}

- (UIColor *)backgroundColorUnselected
{
    UIColor *color = [UIColor colorWithScript:self.attributes[@"backgroundColor"]];
    return color ? color : [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
}
- (UIColor *)backgroundColorSelected
{
    UIColor *color = [UIColor colorWithScript:self.attributes[@"backgroundColorSelected"]];
    return color ? color : [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1.00];
}
@end